"""Miscellaneous helper functions that don't belong in the client code."""
import time
from datetime import datetime

def xmlpath(prefix, url, params=None):
    """Turns a URL of form /account/Characters.xml.aspx into a path
like 12345/12345/Characters.xml."""
    parts = [prefix]
    if params: # This file might be global, thus not have params
        parts.append(params["userID"])
        parts.append(params["characterID"])
    parts.append(url[url.rindex("/")+1:-5])
    filename = '/'.join(parts)

    return filename


def eve2local(eve):
    """Takes a date string from Eve XML and turns it into a local
standard Python datetime object."""
    # Convert to a time tuple
    eve_t = time.strptime(eve, "%Y-%m-%d %H:%M:%S")
    # Convert to a Unix-style timestamp
    eve_u = time.mktime(eve_t)
    # Subtract out the timezone and DST
    local_u = eve_u - time.timezone + time.daylight*3600
    # Convert to local time tuple
    local_t = time.localtime(local_u)

    return datetime(*local_t[:6])

# TODO: make this work when the time is already passed (test inputs!)
def eta_str(future_dt):
    """Takes a python datetime in the future and turns it into an ETA string
of the form "3 days, 1 hour, 41 minutes"."""
    # find difference between future and now
    eta = future_dt - datetime.today()
    secs = eta.seconds
    eta_t = (eta.days, secs/60/60, (secs/60 - (secs/60/60)*60))
    # bits for singularizing intervals
    intervals = ["days", "hours", "minutes"]
    singular = lambda x, y: ( x, (y, y[:-1])[x == 1] )
    # k>0 removes e.g. "0 years", "0 months" from string
    eta_s = ', '.join(["%s %s" % singular(k, v) for \
            k, v in zip(eta_t, intervals) if k > 0])

    return eta_s
